﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using MvcPatch.Routing;
using System.Web.Mvc;

namespace MvcPatch
{
    public static class RouteCollectionExtensions
    {
        public static void MapDomain(
            this RouteCollection routeCollection,
            string prefix,
            string pattern,
            Action<IDictionary<string, RouteBase>> routeCollector)
        {
            routeCollection.MapDomain(prefix, pattern, null, null, routeCollector);
        }

        public static void MapDomain(
            this RouteCollection routeCollection,
            string prefix,
            string pattern,
            object defaults,
            Action<IDictionary<string, RouteBase>> routeCollector)
        {
            routeCollection.MapDomain(prefix, pattern, defaults, null, routeCollector);
        }

        public static void MapDomain(
            this RouteCollection routeCollection,
            string prefix,
            string pattern,
            object defaults,
            object constraints,
            Action<IDictionary<string, RouteBase>> routeCollector)
        {
            var innerRoutes = new Dictionary<string, RouteBase>(StringComparer.OrdinalIgnoreCase);
            routeCollector(innerRoutes);

            prefix = String.IsNullOrEmpty(prefix) ? "" : prefix + ".";
            foreach (var pair in innerRoutes)
            {
                routeCollection.Add(prefix + pair.Key, pair.Value.WithDomain(pattern, defaults, constraints));
            }
        }

        public static void MapFast(
            this RouteCollection routeCollection,
            string name,
            string pattern,
            object defaults)
        { 
            routeCollection.Add(name, new FastRoute(pattern, new RouteValueDictionary(defaults), new MvcRouteHandler()));
        }
    }
}
